<?php

/* 会员控制器 */
class WdexUserApp extends BackendApp
{
	var $_user_mod;

	function __construct()
	{
		$this->WdexUserApp();
	}

	function WdexUserApp()
	{
		parent::__construct();
		$this->_user_mod =& m('member');
		require_once(ROOT_PATH."/eccore/model/mssql.php");
	}

	function index()
	{
		//当前用户类型
		$type  = $this->visitor->get('type');
		$this->assign('type',$type);
		if(!empty($type)){
			echo "您无权操作";exit;
		}
		$conditions = $this->_get_query_conditions(array(
		array(
				'field' => $_GET['field_name'],
				'name'  => 'field_value',
				'equal' => 'like',
		),
		));

		$fx  = empty($_REQUEST['fx'])?0:intval($_REQUEST['fx']);
		
		$where = ' and prevuid=0 and type=10';

		if($fx==1){
			$where.=" and member.fx=1";
		}
		if($fx==2){
			$where.=" and member.fx=0";
		}
		
		if($_GET['hasdepot']==1){
			$where.=" and member.depot<>0 ";
		}
		if($_GET['hasdepot']==2){
			$where.=" and ifnull(member.depot,0)=0 ";
		}

		$hasdepot=array();
		$hasdepot[0]="请选择认证状态";
		$hasdepot[1]="已认证";
		$hasdepot[2]="未认证";
		$this->assign('hasdepot', $hasdepot);

		//更新排序
		if (isset($_GET['sort']) && !empty($_GET['order']))
		{
			$sort  = strtolower(trim($_GET['sort']));
			$order = strtolower(trim($_GET['order']));
			if (!in_array($order,array('asc','desc')))
			{
				$sort  = 'reg_time';
				$order = 'desc';
			}
		}
		else
		{
			if (isset($_GET['sort']) && empty($_GET['order']))
			{
				$sort  = strtolower(trim($_GET['sort']));
				$order = "";
			}
			else
			{
				$sort  = 'reg_time';
				$order = 'desc';
			}
		}
		$page = $this->_get_page();

		$db=&db();
		$sql="SELECT member.*,d1.d_value,p1.o_name, s.store_id,user_priv.store_id as
priv_store_id,user_priv.privs, member.user_id FROM zys_member member 
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 ".$conditions.$where." ORDER BY $sort $order LIMIT ".$page['limit'];

		$users=$db->getAll($sql);

		$sql2="select count(*)  FROM zys_member member
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 ".$conditions.$where;
		$users_count=$db->getone($sql2);

		foreach ($users as $key => $val)
		{
			if ($val['priv_store_id'] == 0 && $val['privs'] != '')
			{
				$users[$key]['if_admin'] = true;
			}

			if($val&&$val['depot']){
				$sqldb=&sqldb();
				$temp="";
				$sql="select NAME from dbo.T_SALM where SAL_NO=".$val['depot'];
				$temp =$sqldb->getOne($sql);
				$users[$key]['depot_name']=$temp;
			}


		}
		$this->assign('users', $users);
		$page['item_count'] = $users_count;
		$this->_format_page($page);
		$this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
		$this->assign('page_info', $page);
		/* 导入jQuery的表单验证插件 */
		$this->import_resource(array(
            'script' => 'jqtreetable.js,inline_edit.js',
            'style'  => 'res:style/jqtreetable.css'
            ));
            $this->assign('query_fields', array(
            'user_name' => '用户名',
            'email'     => '电子邮箱',
            'real_name' => '真实姓名',
            //            'phone_tel' => LANG::get('phone_tel'),
            //            'phone_mob' => LANG::get('phone_mob'),
            ));
            $this->assign('sort_options', array(
            'reg_time DESC'   => '注册时间',
            'last_login DESC' => '最后登录',
            'logins DESC'     => '登录次数',
            ));
            $this->display('wdexuser.index.html');
	}

	function add()
	{
		$user_type = $utype = isset($_GET['utype'])?intval($_GET['utype']):-1;
		//当前用户类型
		$type  = $this->visitor->get('type');
		$this->assign('type',$type);
		$this->assign('utype',$utype);
		if (!IS_POST)
		{


			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
			//是否设置头像
			//$ms =& ms();
			//$this->assign('set_avatar', $ms->user->set_avatar());
			$this->display('wdexuser.form.html');
		}
		else
		{
			$user_name = trim($_POST['user_name']);
			$password  = trim($_POST['password']);
			$email     = trim($_POST['email']);
			$phone_tel = trim($_POST['phone_tel']);

			if (strlen($user_name) < 3 || strlen($user_name) > 25)
			{
				$this->show_warning('user_name_length_error');

				return;
			}

			if (strlen($password) < 6 || strlen($password) > 20)
			{
				$this->show_warning('password_length_error');

				return;
			}

			if(!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", $phone_tel)){

				$this->show_warning('手机错误');
				return;
			}
			/* 连接用户系统 */
			$ms =& ms();

			/* 检查名称是否已存在 */
			if (!$ms->user->check_username($user_name))
			{
				$this->show_warning($ms->user->get_error());
				return;
			}
			if($utype==-1)$user_type =$type;
			$prevuid = $type==0?0:$this->visitor->get('user_id');
			/* 保存本地资料 */
			$data = array(
                'real_name' => trim($_POST['real_name']),
                'gender'    => intval($_POST['gender']),
			    'fx'    => intval($_POST['fx']),
			    'phone_tel' => $_POST['phone_tel'],
				'unit' => intval($_POST['unit']),
				'depot' => intval($_POST['depot']),
				'type' => 10,
				'prevuid'=> $prevuid,
				'giveauth' => isset($_POST['giveauth'])?intval($_POST['giveauth']):0
			//                'phone_mob' => $_POST['phone_mob'],
			//				  'im_qq'     => $_POST['im_qq'],
			// 				  'im_msn'    => $_POST['im_msn'],
			//                'im_skype'  => $_POST['im_skype'],
			//                'im_yahoo'  => $_POST['im_yahoo'],
			//                'im_aliww'  => $_POST['im_aliww'],
			// 				  'reg_time'  => gmtime(),
			);
			if(in_array($utype, array(2,3,4))){
				$data['subtype'] = 1;
			}
			/* 到用户系统中注册 */
			$user_id = $ms->user->register($user_name, $password, $email, $data);
			if (!$user_id)
			{
				$this->show_warning($ms->user->get_error());

				return;
			}

			/*if (!empty($_FILES['portrait']))
			 {
				$portrait = $this->_upload_portrait($user_id);
				if ($portrait === false)
				{
				return;
				}

				$portrait && $this->_user_mod->edit($user_id, array('portrait' => $portrait));
				$portrait && $this->_user_mod->edit($user_id, array('headimgurl' => $portrait));
				}*/


			$this->show_message('添加成功','返回会员', 'index.php?app=wdexuser&act=edit&id='.$user_id);
		}
	}

	/*检查会员名称的唯一性*/
	function  check_user()
	{
		$user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
		if (!$user_name)
		{
			echo ecm_json_encode(false);
			return ;
		}

		/* 连接到用户系统 */
		$ms =& ms();
		echo ecm_json_encode($ms->user->check_username($user_name));
	}

	function edit()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST)
		{
			/* 是否存在 */
			$sql = "select m.*,op.o_name from zys_member as m left join zys_operator as op on m.unit =op.o_tid where m.user_id=".$id;
			$db = &db();
			$user = $db->getRow($sql);
			if (!$user)
			{
				$this->show_warning('user_empty');
				return;
			}
			$type  = $this->visitor->get('type');
			if($type!=0){
				if($type!=$user['type']){
					$this->show_warning('您无权操作');
				}
			}
			if($user&&$user['depot']){
				$sqldb=&sqldb();
				$temp="";
				$sql="select NAME from dbo.T_SALM where SAL_NO=".$user['depot'];
				$temp =$sqldb->getOne($sql);;
				$this->assign('sname',$temp);
			}


			$this->assign('utype',$user['type']);
			/*
			 $ms =& ms();
			 $this->assign('set_avatar', $ms->user->set_avatar($id));*/
			$this->assign('user', $user);
			$this->assign('phone_tel', explode('-', $user['phone_tel']));
			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
			$this->display('wdexuser.form.html');
		}
		else
		{
			$prevuid = $this->visitor->get('type')==0?0:$this->visitor->get('user_id');
			$data = array(
				'real_name' => trim($_POST['real_name']),
				'gender'    => intval($_POST['gender']),
				'fx'    => intval($_POST['fx']),
				'phone_tel' => $_POST['phone_tel'],
				'unit' => intval($_POST['unit']),
				'type' => 10,
				'depot' =>  intval($_POST['depot']),
				'prevuid'=> $prevuid,
				'giveauth' => isset($_POST['giveauth'])?intval($_POST['giveauth']):0
			//                'phone_mob' => $_POST['phone_mob']
			//   			  'im_qq'     => $_POST['im_qq'],
			//                'im_msn'    => $_POST['im_msn'],
			//                'im_skype'  => $_POST['im_skype'],
			//                'im_yahoo'  => $_POST['im_yahoo'],
			//                'im_aliww'  => $_POST['im_aliww'],
			);
			if (!empty($_POST['password']))
			{
				$password = trim($_POST['password']);
				if (strlen($password) < 6 || strlen($password) > 20)
				{
					$this->show_warning('password_length_error');

					return;
				}
			}
			if(!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", trim($_POST['phone_tel']))){

				$this->show_warning('手机错误');
				return;
			}

			/*if (!empty($_FILES['portrait']))
			 {
				$portrait = $this->_upload_portrait($id);
				if ($portrait === false)
				{
				return;
				}
				$data['portrait'] = $portrait;
				$data['headimgurl'] = $portrait;
					
				}*/

			/* 修改本地数据 */
			$this->_user_mod->edit($id, $data);

			/* 修改用户系统数据 */
			$user_data = array();
			!empty($_POST['password']) && $user_data['password'] = trim($_POST['password']);
			!empty($_POST['email'])    && $user_data['email']    = trim($_POST['email']);
			if (!empty($user_data))
			{
				$ms =& ms();
				$ms->user->edit($id, '', $user_data, true);
			}

			$this->show_message('编辑成功','再次编辑',   'index.php?app=wdexuser&act=edit&id=' . $id
			);
		}
	}
	//货主列表
	function choosehz(){
		$db=&db();
		$page = $this->_get_page();
		$o_name=empty($_GET['o_name'])?'':$_GET['o_name'];
		$sqlw=" o_consignor=1 ";
		if($o_name){
			$sqlw.=" and o_name like '%".$o_name."%'";
		}
		$sql="select * from zys_operator WHERE $sqlw";
		$page['item_count'] = $db->getOne($sql);

		$this->_format_page($page);
		$this->assign('page_info', $page);

		$sql="SELECT * FROM zys_operator WHERE $sqlw limit $page[limit]";
		$hz=$db->getAll($sql);
		$this->assign('hz', $hz);
		$this->display('user.choosehz.html');
	}

	//选择承运商
	function chooseop(){
		$db=&db();
		$page = $this->_get_page();

		$o_name=empty($_GET['o_name'])?'':$_GET['o_name'];

		$sqlw=" o_carrier=1 ";
		if($o_name){
			$sqlw.=" and o_name like '%".$o_name."%'";
		}
		$sql="select * from zys_operator WHERE $sqlw";
		$page['item_count'] = $db->getOne($sql);

		$this->_format_page($page);
		$this->assign('page_info', $page);

		$sql="SELECT * FROM zys_operator WHERE $sqlw limit $page[limit]";
		$carrier=$db->getAll($sql);

		$this->assign('carrier', $carrier);

		$this->display('user.chooseop.html');
	}


	function ajax_col()
	{
		$id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$column = empty($_GET['column']) ? '' : trim($_GET['column']);
		$value  = isset($_GET['value']) ? trim($_GET['value']) : '';
		$data   = array();

		if (in_array($column ,array('del')))
		{
			$data[$column] = $value;
			$this->_user_mod->edit($id, $data);
			if(!$this->_user_mod->has_error())
			{
				echo ecm_json_encode(true);
			}
		}
		else
		{
			return ;
		}
		return ;
	}

	function drop()
	{
		$db=&db();
		$id = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$id)
		{
			$this->show_warning('no_user_to_drop');
			return;
		}
		$admin_mod =& m('userpriv');
		if(!$admin_mod->check_admin($id))
		{
			$this->show_message('cannot_drop_admin',
                'drop_admin', 'index.php?app=admin');
			return;
		}

		$ids = explode(',', $id);

		/* 连接用户系统，从用户系统中删除会员 */
		$ms =& ms();
		if (!$ms->user->drop($ids))
		{
			foreach ($ids as $k=>$v){
				$sql="select username from zys_member where user_id=".$v;
				$username=$db->getOne();
					
				/*if($username){
					$url = "http://192.168.0.189:9090/plugins/userService/userservice?type=delete&secret=0wBfHo6f&username=".$username;
					$f = fopen($url,'r');
					$response = fread($f, 1024);
					fclose($f);
					}*/
			}
			$this->show_warning($ms->user->get_error(),'','index.php?app=wdexuser');

			return;
		}

		$this->show_message('删除成功','','index.php?app=wdexuser');
	}

	/**
	 * 上传头像
	 *
	 * @param int $user_id
	 * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
	 */
	function _upload_portrait($user_id)
	{
		$file = $_FILES['portrait'];
		if ($file['error'] != UPLOAD_ERR_OK)
		{
			return '';
		}

		import('uploader.lib');
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE);
		$uploader->addFile($file);
		if ($uploader->file_info() === false)
		{
			$this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=user&amp;act=edit&amp;id=' . $user_id);
			return false;
		}
		$imgname=gmtime();
		$uploader->root_dir(ROOT_PATH);
		return $uploader->save('data/files/mall/portrait/' . ceil($user_id / 500), $imgname);
	}

	//仓库列表
	function choosedepot(){
		$db=&db();
		$page = $this->_get_page();

		$o_name=empty($_GET['o_name'])?'':$_GET['o_name'];


		$sqlw=" 1=1 ";
		if($o_name){
			$sqlw.=" and (SAL_NO like '%".$o_name."%' or NAME like '%".$o_name."%')";
		}

		$page = $this->_get_pagen(8);
		$bindlist=array();
		$sqldb=&sqldb();
		$sql="select * from (select SAL_NO,NAME,ROW_NUMBER() OVER (ORDER BY SAL_NO desc) AS RowNumber from dbo.T_SALM
		where $sqlw) T_SALM where RowNumber > ".$page['s']." 
		AND RowNumber <= ".$page['e']."";
		$bindlist =$sqldb->getAll($sql);

		$this->assign('depot',$bindlist);

		$sql="select count(1) from dbo.T_SALM where $sqlw";
		$c=$sqldb->getOne($sql);
		//$this->json_result($list);

		$page['item_count'] = $c;
		$this->_format_page($page);
		$this->assign('page_info', $page);



		$this->display('wdexuser.choosedepot.html');
	}
	function choosedepotdone(){
		$id=empty($_GET['id'])?0:$_GET['id'];
		$name=empty($_GET['name'])?'':$_GET['name'];
		echo("<script>window.parent.changedepot($id,'".$name."');</script>");
	}


}

?>
